<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tinymce Demo</title>
    <script src="tinymce/tinymce.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>

<body>
<h1>TinyMCE快速开始示例</h1>
<div id="mytextarea"></div>
<button id="submitBtn">展示</button>
<h1>以下是展示</h1>
<div id="display">
    <iframe sandbox="allow-scripts allow-same-origin" style="width:500px; height:450px;border:none" data-alloy-tabstop="true" tabindex="-1" srcdoc="">
    </iframe>
</div>
<script>
    const contentCss=`
        img.img_default{max-width:100%;height: fit-content;}
        img.img_green_border{border: 4px solid green;max-width:100%;}
        img.img_blue_border{border: 4px solid blue;max-width:100%;}
        img.img_red_border{border: 4px solid red;max-width:100%;}
    `;
    tinymce.init({
        selector: '#mytextarea',
        language: 'zh_CN',
        plugins: 'importword powerpaste print preview searchreplace autolink directionality visualblocks visualchars ' +
            'fullscreen image link media template code codesample table charmap hr pagebreak nonbreaking ' +
            'anchor insertdatetime advlist lists wordcount imagetools textpattern help emoticons ' +
            'autosave indent2em autoresize importcss',
        toolbar: 'code undo redo restoredraft importword | cut copy paste pastetext | \
        forecolor backcolor bold italic underline strikethrough link anchor | \
        alignleft aligncenter alignright alignjustify outdent indent | \
        styleselect formatselect fontselect fontsizeselect | bullist numlist | \
        blockquote subscript superscript removeformat | \
        table image media charmap emoticons hr pagebreak insertdatetime print preview |\
         fullscreen | indent2em lineheight',
        height: 650, //编辑器高度
        min_height: 400,
        /*content_css: [ //可设置编辑区内容展示的css，谨慎使用
            '/static/reset.css',
            '/static/ax.css',
            '/static/css.css',
        ],*/
        content_style: contentCss,
        fontsize_formats: '12px 14px 16px 18px 24px 36px 48px 56px 72px',
        font_formats: '微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;',
        link_list: [],
        image_class_list: [
            {title: '默认', value: 'img_default'},
            {
                title: '边框',
                menu: [
                    {title: '绿色边框', value: 'img_green_border'},
                    {title: '蓝色边框', value: 'img_blue_border'},
                    {title: '红色边框', value: 'img_red_border'}
                ]
            }
        ],
        importcss_append: true,
        toolbar_sticky: true,
        autosave_ask_before_unload: false,
        //自定义文件选择器的回调内容
        file_picker_callback: function (callback, value, meta) {
            var filetype = '.pdf, .txt, .zip, .rar, .7z, .doc, .docx, .xls, .xlsx, .ppt, .pptx, .mp3, .mp4';
            //后端接收上传文件的地址
            //为不同插件指定文件类型及后端地址
            switch (meta.filetype) {
                case 'image':
                    filetype = '.jpg, .jpeg, .png, .gif';
                    break;
                case 'media':
                    filetype = '.mp3, .mp4';
                    break;
                case 'file':
                default:
            }
            //模拟出一个input用于添加本地文件
            var input = document.createElement('input');
            input.setAttribute('type', 'file');
            input.setAttribute('accept', filetype);
            input.click();
            input.onchange = function () {
                var file = this.files[0];
                var xhr, formData;
                console.log(file.name);
                xhr = new XMLHttpRequest();
                xhr.withCredentials = false;

                xhr.open('POST', "upload"/*FileController 里面的路径*/);
                xhr.onload = function () {
                    if (xhr.status !== 200) {
                        throw new Error('HTTP Error: ' + xhr.status);
                    }
                    let result = JSON.parse(xhr.responseText);
                    if (result.success) {
                        if (meta.filetype === 'file') {
                            //第一个参数是可访问的图片url路径
                            callback(result.data[0], {classes: [], text: file.name});
                        }
                        if (meta.filetype === 'image') {
                            callback(result.data[0], {alt: file.name});
                        }
                        if (meta.filetype === 'media') {
                            callback(result.data[0]);
                        }
                    } else {
                        throw new Error(result.message);
                    }
                };
                formData = new FormData();
                formData.append('file', file, file.name);
                xhr.send(formData);
            }
        },
        images_upload_handler: function (blobInfo, callback, failFun, progress) {
            var file = new File([blobInfo.blob()], blobInfo.filename());
            var xhr, formData;
            console.log(file.name);
            xhr = new XMLHttpRequest();
            xhr.upload.onprogress = function (e) {
                progress(e.loaded / e.total * 100);
            };
            xhr.withCredentials = false;
            xhr.open('POST', "upload"/*FileController 里面的路径*/);
            xhr.onload = function () {
                if (xhr.status !== 200) {
                    failFun('HTTP Error: ' + xhr.status);
                }
                let result = JSON.parse(xhr.responseText);
                if (result.success) {
                    //第一个参数是可访问的图片url路径
                    callback(result.data[0], {alt: file.name, classes: []});
                } else {
                    failFun(result.message);
                }
            };
            formData = new FormData();
            formData.append('file', file, file.name);
            xhr.send(formData);
        }
    });
    $("#submitBtn").click(function () {
        let content = tinymce.get("mytextarea").getContent();
        console.log(content)
        const srcdoc=`<!DOCTYPE html>
        <html>
        <head>
        <base href="http://localhost:2333/">
        <link type="text/css" rel="stylesheet" href="http://localhost:2333/tinymce/skins/ui/oxide/content.min.css">
        <link type="text/css" rel="stylesheet" href="http://localhost:2333/tinymce/skins/content/default/content.css">
        <style type="text/css">
            ${contentCss}
        </style>
        </head>
        <body id="tinymce" class="mce-content-body ">
        ${content}
        <script>
        document.addEventListener && document.addEventListener("click", function(e) {for (var elm = e.target; elm; elm = elm.parentNode) {if (elm.nodeName === "A" && !(e.ctrlKey && !e.altKey)) {e.preventDefault();}}}, false);
        </scr`+`ipt>
        </body>
        </html>`;
        $("#display iframe").attr(`srcdoc`,srcdoc)
    })
</script>
</body>

</html>
